package com.joesem.sale.client.logic.event

import android.os.Bundle
import android.util.Log
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.google.android.material.tabs.TabLayoutMediator
import com.jiaxing.sale.client.databinding.ActivityEventListBinding
import com.jiaxing.sale.client.databinding.LayoutToolbarBinding
import com.joesem.sale.client.base.BaseActivity
import com.joesem.sale.client.base.BaseFragment
import com.joesem.sale.client.base.visible
import com.joesem.sale.client.utils.click

class EventListActivity : BaseActivity<ActivityEventListBinding>() {
    private val titles = mutableListOf("待分配", "已分配", "已完成")
    private val fragments =
        mutableListOf<EventContentListFragment>(BaseFragment.newInstance(Bundle().apply {
            putString("state", titles[0])
        }), BaseFragment.newInstance(Bundle().apply {
            putString("state", titles[1])
        }), BaseFragment.newInstance(Bundle().apply {
            putString("state", titles[2])
        })
        )
    var filterParams: EventFilterMultipleMode? = null

    override fun LayoutToolbarBinding.toolbar(savedInstanceState: Bundle?) {
        visible()
        toolbarTheme()
        toolbarTitle.text = "事件"
    }

    override fun ActivityEventListBinding.initView(savedInstanceState: Bundle?) {

        vpContent.adapter = object : FragmentStateAdapter(supportFragmentManager, lifecycle) {

            override fun getItemCount() = fragments.size

            override fun createFragment(position: Int) = fragments[position]
        }
        val tabAttach = TabLayoutMediator(
            tbaTitle, vpContent, true
        ) { tab, position ->
            tab.text = titles[position]
        }
        tabAttach.attach()
        lifecycle.addObserver(object : DefaultLifecycleObserver {
            override fun onDestroy(owner: LifecycleOwner) {
                tabAttach.detach()
            }
        })
    }

    override fun ActivityEventListBinding.initListener() {
        tvEventType.click {
            optionEventFilter(supportFragmentManager, filterParams) { filter ->
                Log.i("打印", "筛选: $filter")
                filterParams = filter
                tvEventType.text =
                    if (filter.date?.code.isNullOrEmpty() && filter.about_me?.code.isNullOrEmpty() && filter.type?.code.isNullOrEmpty()) {
                        "全部"
                    } else {
                        "已筛选"
                    }
                fragments.forEach { it.refresh() }

            }
        }
    }
}